package com.lelaohui.net.netmanager;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.lelaohui.net.api.Api;
import com.lelaohui.net.request.IRequest;
import com.lelaohui.net.LeLaoHuiApplication;
import com.lelaohui.net.listener.NetDataListener;
import com.lelaohui.net.listener.ProgressListener;
import com.lelaohui.net.response.ResponseBean;
import com.lelaohui.net.response.ResponseBean2;
import com.lelaohui.net.api.ServiceApi;
import com.lelaohui.net.utils.UrlsTools;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.converter.gson.GsonConverterFactory;


public class ServerNetRequestManager implements INetRequestManager {
    private NetManager net;
    private String TAG = "ServerNetRequest";
    private static ServerNetRequestManager requestManager = null;
    private ProgressListener progressListener;
    public static final String SUCCESS_CODE = "200";
    private LocalBroadcastManager broadcastManager = null;

    private ServerNetRequestManager() {
       netManager = new NetManager.NetManagerBuilder();
        netManager.buildConfig(new NetManager.Config());
        netManager.buildConverterFactory(GsonConverterFactory.create());
//        netManager.buildRetrofitBuilderUrl(UrlsTools.SERVER_REQ_URL);
//        net=netManager.build();
    }

    public static ServerNetRequestManager getInstance() {
        if (requestManager == null) {
            synchronized (ServerNetRequestManager.class) {
                if (requestManager == null) {
                    requestManager = new ServerNetRequestManager();
                }
            }
        }
        return requestManager;
    }

    public void postRequest(@NonNull final IRequest request, @NonNull final NetDataListener dataCallback) {
        if (request.isNeedProgress()) {
            try {
                showProgress();
            } catch (Exception e) {
            }
        }
        if ("".equals(request.getReqType())) {
            Log.d(TAG, "serReqNetManager===");
            serReqNetManager(request, dataCallback);
        } else {
            Log.d(TAG, "reqNetManager===");
            reqNetManager(request, dataCallback);
        }
    }
    private void reqNetManager(@NonNull final IRequest request, @NonNull final NetDataListener dataCallback) {
        if (TextUtils.isEmpty(request.getIp())) {
            request.setIp(UrlsTools.REQ_URL);
        }
        create(request.getIp());
        Api api = net.getRetrofit().create(Api.class);
        Call<ResponseBean> call = null;
        if (UrlsTools.ADDRESS_REQ_URL.equals(request.getUriType())) {
            call = api.getAddressFormUrlEncode(request.getUri(), request.getParam());
        } else if (UrlsTools.CAMMER_REQ_URL.equals(request.getUriType())) {
            call = api.getVideoFormUrlEncode(request.getUri(), request.getParam());
        } else if (UrlsTools.MSG_INFO.equals(request.getUriType())) {
            call = api.getMsgFormUrlEncode(request.getUri(), request.getParam());
        }
//        else if (UrlsTools.FOOD_INFO.equals(request.getUriType())) {
//            Log.d(TAG, "request.getUriType()==" + request.getUriType());
//            call = api.getfoodFormUrlEncode(request.getUri(), request.getParam());
//        }
        else if (UrlsTools.ACCOUNT_INFO.equals(request.getUriType())) {
            call = api.getAccFormUrlEncode(request.getUri(), request.getParam());
        } else if (UrlsTools.USER_INFO.equals(request.getUriType())) {
            call = api.getUserInfoFormUrlEncode(request.getUri(), request.getParam());
        } else if (UrlsTools.SERVER_KUC_INFO.equals(request.getUriType())) {
            Log.d(TAG, "--dcdsfasd---" + request.getReqType());
            call = api.postSerInfoEncodeNew(request.getUri(), request.getParam());
        } else {
            call = api.getFormUrlEncode(request.getUri(), request.getParam());
        }
        call.enqueue(new Callback<ResponseBean>() {
            @Override
            public void onResponse(Call<ResponseBean> call, Response<ResponseBean> response) {
                ResponseBean responBean = response.body();
                if (responBean != null) {
                    if (responBean.getRs() != null) {
                        Log.d(TAG, "responBean.getRs()==" + responBean.getRs());
                    }
                    if ("0".equals(responBean.getCode())) {
                        if (responBean.getRs() != null) {
                            String data = new Gson().toJson(responBean.getRs());
                            Log.d(TAG, "Netmanage data===" + data);
                            dataCallback.onNext(data, responBean.getCode());
                        } else {
                            if (response.message() != null) {
                                Log.d(TAG, "response.code()www==" + response.code());
                                dataCallback.onNext("", responBean.getCode());

                                sendBroMessage(response.message());
                            }
                        }
                    } else {
                        Log.d(TAG, "response.code()qqq==" + responBean.getCode());
                        if (responBean.getCode() != null) {
                            dataCallback.onNext("", responBean.getCode());
                            sendBroMessage(responBean.getCode());
                        }
                    }
                }

                if (request.isNeedProgress()) {
                    try {
                        hideProgress();
                    } catch (Exception e) {

                    }

                }
            }

            @Override
            public void onFailure(Call<ResponseBean> call, Throwable t) {
                dataCallback.onError(t);
                if (request.isNeedProgress()) {
                    try {
                        hideProgress();
                    } catch (Exception e) {
                    }
                }
            }
        });
    }

    public void serReqNetManager(@NonNull final IRequest request, @NonNull final NetDataListener dataCallback) {
        if (TextUtils.isEmpty(request.getIp())) {
            request.setIp(UrlsTools.SERVER_REQ_URL);
        }
        create(request.getIp());
        ServiceApi api = net.getRetrofit().create(ServiceApi.class);
        Call<ResponseBean2> call = null;

         if (UrlsTools.SERVER_TASK_REQ.equals(request.getUriType())) {
            call = api.postFormMobleEncodeNew(request.getUri(), request.getParam());
        }else   if (UrlsTools.SERVER_KUC_INFO.equals(request.getUriType())) {
             call = api.postSerKuncunEncodeNew(request.getUri(), request.getParam());
        }  else {
            call = api.postFormUrlEncodeNew(request.getUri(), request.getParam());
        }
        call.enqueue(new Callback<ResponseBean2>() {
            @Override
            public void onResponse(Call<ResponseBean2> call, Response<ResponseBean2> response) {
                ResponseBean2 responBean = response.body();
                if (responBean == null) {
                    return;
                }
                Log.i(TAG, "onResponse: " + responBean.toString());
                if (SUCCESS_CODE.equals(responBean.getCode())) {
                    String json = responBean.getObj();

                    try {
                        dataCallback.onNext(new Gson().fromJson(json.toString(), request.getType()), responBean.getCode());
                    } catch (Exception e) {
                        if (json == null) {
                            dataCallback.onNext("", responBean.getCode());
                            return;
                        } else {
                            dataCallback.onNext(json, responBean.getCode());
                        }
                    }
                } else {
                    if (responBean.getCode() != null) {
                        Log.d(TAG, "MSG==" + responBean.getCode());
                        dataCallback.onNext("", responBean.getCode());
                        sendBroMessage(responBean.getCode());
                    }
                    String json = responBean.getObj();
                    if (json == null) {
                        dataCallback.onNext("", responBean.getCode());
                        return;
                    } else {
                        dataCallback.onNext("", responBean.getCode());
                        return;
                    }
                }
                if (request.isNeedProgress()) {
                    try {
                        hideProgress();
                    } catch (Exception e) {
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBean2> call, Throwable t) {
                dataCallback.onError(t);
                if (request.isNeedProgress()) {
                    try {
                        hideProgress();
                    } catch (Exception e) {
                    }
                }
            }
        });
    }


    public void setProgressListener(ProgressListener progressListener) {
        this.progressListener = progressListener;
    }

    public void showProgress() {
        if (this.progressListener != null) {
            this.progressListener.showProgress();
        }
    }

    public void hideProgress() {
        if (this.progressListener != null) {
            this.progressListener.hideProgress();
        }
    }

    public void sendBroMessage(String msg) {
        Intent intent = new Intent(LeLaoHuiApplication.PROMOT_ACTION);
        intent.putExtra(LeLaoHuiApplication.PROMOT_KEY, msg);
        broadcastManager.sendBroadcast(intent);
    }

    public void setContext(Context context) {
        broadcastManager = LocalBroadcastManager.getInstance(context);
    }

    public void create(String url) {
        if (TextUtils.isEmpty(url)) {
            url = UrlsTools.SERVER_REQ_URL;
            Log.d(TAG, "URL111==" + url);
        }
        Log.d(TAG, "URL2222==" + url);
        netManager.buildRetrofitBuilderUrl(url);
        net = netManager.build();
    }

    private NetManager.NetManagerBuilder netManager;
}
